<?php
/**
 * @param email     varchar
 * @param password  varchar
 */

require_once('rb.php');
R::setup('mysql:host=ftp.giemiebier.nl:3306;dbname=personify', 'school', 'admin123');

$return = array();
if (isset($_POST['email']) && $_POST['email'] != ""
        && isset($_POST['password']) && $_POST['password'] != "") {

    $email = $_POST['email'];
    $wachtwoord = $_POST['password'];
    $id = checkLogin($email, $wachtwoord);

    if ($id != NULL) {
        $return = array();
        $return['login'] = "succes";
        $return['id'] = $id;
        $_SESSION['login'] = true;
        $_SESSION['id'] = $id;
    } else {
        $return['error'] = "No valid email or password";
        $return["login"] = "Login failed";
    }
} else {
    $return['error'] = "No details entered";
    $return['login'] = "Login failed";
}
echo json_encode($return);

function checkLogin($email, $wachtwoord) {
    $password = makeHash($wachtwoord);
    $test=R::findOne("users","emailaddress=? AND password = ?",array($email, $password));
    if($test == null){
       return null;
    }else{
        return $test->id;
    }
}

function makeHash($var) {
    $iterations = 10;
    $salt = '$1$qiejdren$';
    $hash = crypt($var, $salt);
    for ($i = 0; $i < $iterations; ++$i) {
        $hash = crypt($hash . $var, $salt);
    }
    return $hash;
}

?>
